<?php
/**
 * Joomla! 1.5 component jhtraq
 *
 * @version $Id: helper.php 2010-03-09 08:28:06 svn $
 * @author JHShop
 * @package Joomla
 * @subpackage jhtraq
 * @license GNU/GPL
 *
 * Traq type system for Joomla
 *
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

/**
 * jhtraq Helper
 *
 * @package Joomla
 * @subpackage jhtraq
 * @since 1.5
 * @TODO Clean up some unneeded garbage!
 */
class JhtraqHelper {
	
	static private $models = array(); // Return the instance of the model rather than re-create it!
	static private $registry = array(); // Registry! Maybe used maybe not, will be determined as the code grows
	static private $settings = array(); // Depreciated.....
	
	/**
	 * @name getModel
	 * @public
	 * @param $name - name of the model needed
	 * @return object
	 */
	function getModel($name)
	{
		if(!isset(self::$models[$name]))
		{
			if(file_exists(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_jhtraq'.DS.'models'.DS.$name.'.php'))
			{
				require_once( JPATH_ADMINISTRATOR.DS.'components'.DS.'com_jhtraq'.DS.'models'.DS.$name.'.php');
			}else{
				require_once( JPATH_ADMINISTRATOR.DS.'components'.DS.'com_jhtraq'.DS.'models'.DS. $name.'.class.php');
			}
			$classname = 'JhtraqModel' . ucfirst($name);
			self::$models[$name] = new $classname();
		}
			
		
		return self::$models[$name];
	}
	
	/**
	 * @name set
	 * @public
	 * @param $key - key for the registry object
	 * @param $value - Value of the registry object
	 * @return null
	 */
	function set($key,$value)
	{
		self::$registry[$key] = $value;
	}
	
	/**
	 * @name get
	 * @public
	 * @param $key
	 * @return registry object
	 */
	function get($key)
	{
		return self::has($key)?self::$registry[$key]:null;
	}
	
	/**
	 * @name has
	 * @public
	 * @param $key
	 * @return bool
	 */
	function has($key)
	{
		return isset(self::$registry[$key]);
	}
	
	/**
	 * @name getSetting
	 * @public
	 * @param $key
	 * @return string
	 * @note depreciated from Alpha 3
	 */
	function getSetting($key)
	{
		
		if(!count(self::$settings))
		{
			$model = self::getModel('jhtraq');
			self::$settings = $model->getConfig();
		}
		return self::$settings[$key];
		
	}
	
	/**
	 * @name drawTabs
	 * @public
	 * @param $slug - Projects slug
	 * @return string
	 */
	function drawTabs($slug)
	{
		$page = JRequest::getVar('view');
		$j_user = JFactory::getUser();
		$model = self::getModel('jhtraq');
		$user = $model->getUserPerms($j_user->id);
		$project = $model->getProjectBySlug($slug);
		$document =& JFactory::getDocument();
		
		$page_translation = "COM_JHTRAQ_" . strtoupper($page);
		$pageTitle = $project->name . '::' . JText::_($page_translation);
		$document->setTitle($pageTitle);
		$userGroup = $model->GetMyGroup();
		//print_r($user);
		$xhtml = self::genCSS();
		$xhtml .= '
		
		<div id="jhtnav">
		<ul class="main_nav">
			<li class="first';
			if($page == 'projects') $xhtml .= ' active';
		$xhtml .= '">
				<a href="'. JRoute::_('index.php?option=com_jhtraq&view=projects&project='.$slug) . '">'. JText::_('COM_JHTRAQ_PROJECT_INFORMATION') . '</a>
			</li>
			<li class="';
			if($page == 'roadmap')$xhtml .= ' active';
			$xhtml .= '">
				<a href="'. JRoute::_('index.php?option=com_jhtraq&view=roadmap&project='.$slug) . '">'. JText::_('COM_JHTRAQ_ROADMAP') . '</a>
			</li>
			<li class="';
			if($page == 'timeline')$xhtml .= ' active';
			$xhtml .= '">
				<a href="'. JRoute::_('index.php?option=com_jhtraq&view=timeline&project='.$slug) . '">'. JText::_('COM_JHTRAQ_TIMELINE') . '</a>
			</li>
			<li class="';
			if($page == 'tickets')$xhtml .= ' active';
			$xhtml .= '">
				<a href="'. JRoute::_('index.php?option=com_jhtraq&view=tickets&project='.$slug) . '">'. JText::_('COM_JHTRAQ_TICKETS') . '</a>
			</li>
			<li class="';
			if($page == 'changelog')$xhtml .= ' active';
			$xhtml .= '">
				<a href="'. JRoute::_('index.php?option=com_jhtraq&view=changelog&project='.$slug) . '">'. JText::_('COM_JHTRAQ_CHANGELOG') . '</a>
			</li>
			<li class="';
			if($page == 'wiki')$xhtml .= ' active';
			$xhtml .= '">
			<a href="'. JRoute::_('index.php?option=com_jhtraq&view=wiki&project='.$slug) . '">'. JText::_('COM_JHTRAQ_WIKI') . '</a>
			</li>'
			;
			
			//SVN
			if((in_array($userGroup['group_id'], explode(",", $this->project->browse_svn)) || 
				in_array($userGroup['group_id'], explode(",", $this->project->svn_logs))) && $project->svn_url != '')
			{
				$xhtml .= '<li class="';
				if($page == 'svn')$xhtml .= ' active';
				$xhtml .= '">
				<a href="'. JRoute::_('index.php?option=com_jhtraq&view=svn&project='.$slug) . '">'. JText::_('COM_JHTRAQ_SVN') . '</a>
				</li>';
			}
			
			
			//releases::
			$db =& JFactory::getDBO();
			$db->setQuery("Select count(*) as cnt from #__jhtraq_releases where project_id = '".$project->id."' and published='1' order by released desc");
			$cnt = $db->loadResult();
			//print_r($db);
			if($cnt)
			{
				$xhtml .= '<li class="';
				if($page == 'releases')$xhtml .= ' active';
				$xhtml .= '">
				<a href="'. JRoute::_('index.php?option=com_jhtraq&view=releases&project='.$slug) . '">'. JText::_('COM_JHTRAQ_RELEASES') . '</a>
				</li>';
			}
			//create tickets!!!
			
			//Ok 1 lets check if they need a subscription!!!
                        $addtickets = true;
                        if($this->project->amibros_tickets != '' && $this->project->amibros_tickets != 0)
                        {
                            $addtickets = false;
                            if(file_exists(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_ambrasubs' . DS . 'ambrasubs.php'))
                            {
                               //$j_user->id
                                $ambras = explode(",",$this->project->amibros_tickets);
                                 foreach($ambras as $type) {
                                    if($addtickets) continue;
                $isUserA = AmbrasubsHelperSubscription::isUser( $j_user->id, $type, '1', '1' );
                if (!is_object($isUserA) || $isUserA->status != '1') {
                    /* the user has NO active subscription, so do some kind of action */
                } else {
                    /* the user HAS an active subscription, so do something else */
                    $addtickets = true;
                }
            }
                                
                            }else{
                                $addtickets = true;
                            }
                        }
                        
            if(in_array($j_user->id, explode(",",$project->managers)))
            {
				$addtickets = true;
		}            


			if(in_array($userGroup['group_id'], explode(",", $this->project->add_tickets)) && $addtickets)
			{
				$xhtml .= '			
				<li class="standalone';
				if($page == "newticket")$xhtml .= ' active';
				$xhtml .= '">
				<a href="'. JRoute::_('index.php?option=com_jhtraq&view=newticket&project='.$slug) . '">'. JText::_('COM_JHTRAQ_NEW_TICKET') . '</a>
				</li>';
			}
				
		$xhtml .= '</ul></div>';
		

		return $xhtml;
		
	}
	
	/**
	 * @name getPercent
	 * @public
	 * @param $min
	 * @param $max
	 * @return int
	 */
	function getPercent($min,$max)
	{
		if($min == $max) return 100;
		
		$calculate = ($min/$max*100);
		$split = explode('.',$calculate);
		return $split[0];
	}
	
	/**
	 * @name timesince
	 * @public
	 * @param $original
	 * @param $detailed
	 * @return string
	 */
	function timesince($original, $detailed = false)
	{
		$now = time(); // Get the time right now...
		
		// Time chunks...
		$chunks = array(
				array(60 * 60 * 24 * 365, 'year', 'years'),
				array(60 * 60 * 24 * 30, 'month', 'months'),
				array(60 * 60 * 24 * 7, 'week', 'weeks'),
				array(60 * 60 * 24, 'day', 'days'),
				array(60 * 60, 'hour', 'hours'),
				array(60, 'minute', 'minutes'),
				array(1, 'second', 'seconds'),
			);
						
		// Get the difference
		$difference = ($now - $original);
		
		// Loop around, get the time since
		for($i = 0, $c = count($chunks); $i < $c; $i++)
		{
			$seconds = $chunks[$i][0];
			$name = $chunks[$i][1];
			$names = $chunks[$i][2];
			if(0 != $count = floor($difference / $seconds)) {
				break;
			}
		}
		
		// Format the time since
		//$since = $count." ".((1 == $count) ? $name : $names);
		$since = self::l('x_'.((1 == $count) ? $name : $names),$count);
		
		// Get the detailed time since if the detaile variable is true
		if($detailed && $i + 1 < $c)
		{
			$seconds2 = $chunks[$i + 1][0];
			$name2 = $chunks[$i + 1][1];
			$names2 = $chunks[$i + 1][2];
			if(0 != $count2 = floor(($difference - $seconds * $count) / $seconds2))
			$since = self::l('x_and_x',$since,self::l('x_'.((1 == $count2) ? $name2 : $names2),$count2));
		}
		
		// Return the time since
		return $since;
	}
	
	/**
	 * @name timefrom
	 * @public
	 * @param $original
	 * @param $detailed
	 * @return string
	 */
	function timefrom($original, $detailed = false)
	{
		$now = time(); // Get the time right now...
		
		// Time chunks...
		$chunks = array(
					array(60 * 60 * 24 * 365, 'year', 'years'),
					array(60 * 60 * 24 * 30, 'month', 'months'),
					array(60 * 60 * 24 * 7, 'week', 'weeks'),
					array(60 * 60 * 24, 'day', 'days'),
					array(60 * 60, 'hour', 'hours'),
					array(60, 'minute', 'minutes'),
					array(1, 'second', 'seconds'),
			);
						
		// Get the difference
		$difference = ($original - $now);
		
		// Loop around, get the time from
		for($i = 0, $c = count($chunks); $i < $c; $i++)
		{
			$seconds = $chunks[$i][0];
			$name = $chunks[$i][1];
			$names = $chunks[$i][2];
			if(0 != $count = floor($difference / $seconds)) {
				break;
			}
		}
		
		// Format the time from
		$from = self::l('x_'.((1 == $count) ? $name : $names),$count);
		
		// Get the detailed time from if the detaile variable is true
		if($detailed && $i + 1 < $c)
		{
			$seconds2 = $chunks[$i + 1][0];
			$name2 = $chunks[$i + 1][1];
			$names2 = $chunks[$i + 1][2];
			if(0 != $count2 = floor(($difference - $seconds * $count) / $seconds2))
			$from = self::l('x_and_x',$from,self::l('x_'.((1 == $count2) ? $name2 : $names2),$count2));
		}
		
		// Return the time from
		return $from;
	}
	
	
	/**
	 * @name l
	 * @public
	 * @param $string
	 * @param $vars
	 * @return $string
	 */
	function l($string,$vars=array())
	{
		$lang['x_seconds'] = '@1@ '. JText::_('COM_JHTRAQ_SECONDS');
		$lang['x_minutes'] = '@1@ '. JText::_('COM_JHTRAQ_MINUTES');
		$lang['x_hours'] = '@1@ '. JText::_('COM_JHTRAQ_HOURS');
		$lang['x_days'] = '@1@ '. JText::_('COM_JHTRAQ_DAYS');
		$lang['x_weeks'] = '@1@ '. JText::_('COM_JHTRAQ_WEEKS');
		$lang['x_months'] = '@1@ '. JText::_('COM_JHTRAQ_MONTHS');
		$lang['x_years'] = '@1@ '. JText::_('COM_JHTRAQ_YEARS');
		$lang['x_second'] = '@1@ '. JText::_('COM_JHTRAQ_SECOND');
		$lang['x_minute'] = '@1@ '. JText::_('COM_JHTRAQ_MINUTE');
		$lang['x_hour'] = '@1@ '. JText::_('COM_JHTRAQ_HOUR');
		$lang['x_day'] = '@1@ '. JText::_('COM_JHTRAQ_DAY');
		$lang['x_week'] = '@1@  '. JText::_('COM_JHTRAQ_WEEK');
		$lang['x_month'] = '@1@ '. JText::_('COM_JHTRAQ_MONTH');
		$lang['x_year'] = '@1@ '. JText::_('COM_JHTRAQ_YEAR');
		$lang['x_and_x'] = '@1@ '. JText::_('COM_JHTRAQ_AND').' @2@';
		$lang['completed_on_x'] = JText::_('COM_JHTRAQ_COMPLETED') . ' @1@';
		
		$lang['timeline_open_ticket'] = '@1@ '.JText::_('COM_JHTRAQ_OPENED_TICKET').' #@2@ (@3@)';
		$lang['timeline_close_ticket'] = '@1@ '.JText::_('COM_JHTRAQ_CLOSED_TICKET').' #@2@ (@3@)';
		$lang['timeline_reopen_ticket'] = '@1@ '.JText::_('COM_JHTRAQ_REOPENED_TICKET').' #@2@ (@3@)';
		
		$lang['ticket_history_type'] = JText::_('COM_JHTRAQ_CHANGED_TYPE');
		$lang['ticket_history_version'] = JText::_('COM_JHTRAQ_CHANGED_VERSION');
		$lang['ticket_history_milestone'] = JText::_('COM_JHTRAQ_CHANGED_MILESTONE');
		$lang['ticket_history_component'] = JText::_('COM_JHTRAQ_CHANGED_COMPONENT');
		$lang['ticket_history_severity'] = JText::_('COM_JHTRAQ_CHANGED_SEVERIY');
		$lang['ticket_history_priority'] = JText::_('COM_JHTRAQ_CHANGED_PRIORITY');
		$lang['ticket_history_summary'] = JText::_('COM_JHTRAQ_CHANGED_SUMMARY');
		$lang['ticket_history_assigned_to'] = JText::_('COM_JHTRAQ_CHANGED_ASSIGNED');
		$lang['ticket_history_status_open'] = JText::_('COM_JHTRAQ_OPENED_TICKET');
		$lang['ticket_history_status_mark'] = JText::_('COM_JHTRAQ_CHANGED_STATUS');
		$lang['ticket_history_status_close'] = JText::_('COM_JHTRAQ_CLOSED_TICKET');
		$lang['ticket_history_status_reopen'] = JText::_('COM_JHTRAQ_REOPENED_TICKET');
		$lang['ticket_history_private_public'] = JText::_('COM_JHTRAQ_MARKED_TICKET');
		$lang['ticket_history_private_private'] = JText::_('COM_JHTRAQ_MARKED_PRIVATE');
		
		// Check if the string exists
		if(!isset($lang[$string])) return '['.$string.']';
		
		// Get the locale string
		$string = $lang[$string];
		
		// Check if the $vars is an array or use the function args.
		if(!is_array($vars)) $vars = array_slice(func_get_args(),1);
		
		// Loop through the vars and replace the the {x} stuff
		foreach($vars as $var)
		{
			@++$v;
			$string = str_replace('@'.$v.'@',$var,$string);
		}
		
		
		return $string;
	}
	
	/**
	 * TODO MOVE THIS TO THE MAIN CONTROLLER FILE
	 */
	function genCSS()
	{
		$document =& JFactory::getDocument();
		$document->addStyleSheet(JURI::root() . "components/com_jhtraq/css.css");
		
		return '';
	}
		
	/**
	 * @name formattext
	 * @public
	 * @param $text
	 * @return string
	 */
	function formattext($text)
	{
		
		$text = preg_replace("/\[ticket:(.*?)\\]/is",'<a href="'. JRoute::_('index.php?option=com_jhtraq&view=tickets&layout=view&project=' . JRequest::getVar('project') . '&ticket=') . '$1">['. JText::_('COM_JHTRAQ_TICKET') . ' #$1]</a>',$text );
		
		//We should inc this into the wiki BBcode!!!	
		
		$text = nl2br($text);
		return $text;
	}
		
	/**
	 * @name iif
	 * @public
	 * @param $condition
	 * @param $true
	 * @param $false
	 * @return $true / $false
	 * @note to be depreciated
	 */
	function iif($condition, $true, $false='')
	{
		return ($condition ? $true : $false);
	}
	
	/**
	 * @name isallowed
	 * @public
	 * @param $key
	 * @return bool
	 */
	function isallowed($key)
	{
		$gid = 3;
		$arr = explode(",",$key);
		$user =& JFactory::getUser();
		if($user->id)
		{
			$db =& JFactory::getDBO();
			$db->setQuery("Select group_id from #__jhtraq_users where id='".$user->id."'");
			$gid = $db->loadResult();
		}
		return in_array($gid,$arr);
	}
	
	/**
	 * @name renderWikititle
	 * @public
	 * @param $pagename
	 * @return string
	 */
	function renderWikiTitle($pagename = '')
	{
		if($pagename == '')
			$pagename = JRequest::getVar('page');
		
		$title = str_replace("_"," ", $pagename);
		
		$array = preg_split('/([A-Z]+[^A-Z]*)/', $title, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
		$title = implode(" ", $array);
		
		return $title;
		
	}
	
	/**
	 * @name sendMail
	 * @public
	 * @param mixed $to either string or array
	 * @param $subject
	 * @param $body
	 * @param $html
	 */
	 function sendMail($to,$subject,$body,$html = true)
	 {
		 $mailer =& JFactory::getMailer();
		 $config =& JFactory::getConfig();
		 $sender = array( 
					$config->getValue( 'config.mailfrom' ),
					$config->getValue( 'config.fromname' )
		 );
						 
		$mailer->setSender($sender);
		$mailer->addRecipient($to);
		$mailer->setSubject($subject);
		$mailer->isHTML($html);
		$mailer->setBody($body);
		$send =& $mailer->Send();
		
	
	 }

}
?>
